var RestClient = require('/utils/remotedata/RestClient');

var configuracionSaved = null;
var paramsSaved = null;

exports.invocar = function(configuracion, params, callbackExito, callbackError) {
	Ti.API.debug("AuthClient :: invocar" + JSON.stringify(params) );
	RestClient.setReconnect(null);
	invocarRestClient(configuracion, params, callbackExito, callbackError); 
};

function invocarRestClient(configuracion, params, callbackExito, callbackError, login ) {
	var callbackExitoLocal = function(data){
		Ti.API.debug("AuthClient :: params saved..." );
		configuracionSaved = configuracion;
		paramsSaved = params;
		callbackExito(data);
		RestClient.setReconnect(doReconnect);
	};
	
	var callbackErrorLocal = function(data1, data2){
		configuracionSaved = null;
		paramsSaved = null;
		callbackError(data1, data2);
		RestClient.setReconnect(null);
	};	
	
	RestClient.invocar(configuracion, params, callbackExitoLocal, callbackErrorLocal);
}

exports.reconnect = function(server, request, callbackExito, callbackError, contentType, retry) {
	doReconnect(server, request, callbackExito, callbackError, contentType, retry);
};

function doReconnect(server, request, callbackExito, callbackError, contentType, retry) {	
	Ti.API.debug("AuthClient :: reconnect..." );
	var callbackExitoLocal = function(data){
		Ti.API.debug("AuthClient :: retry..." );
		retry(server, request, callbackExito, callbackError, contentType);
	};
	
	var callbackErrorLocal = function(data1, data2){
		Ti.API.debug("AuthClient :: error on reconnect..." );
		callbackError();
	};	

	if( configuracionSaved !== null && paramsSaved !== null ) {
		Ti.API.debug("AuthClient :: call reconnect..." );
		invocarRestClient(configuracionSaved, paramsSaved, callbackExitoLocal, callbackErrorLocal); 
	} else {
		// no info for reconnect...
		Ti.API.debug("AuthClient :: no info for reconnect..." );
		callbackError();
	}
	
}
